﻿using DimensionsHelper.Common.Metadata;
using DimensionsHelper.LanguageService.Syntax;

namespace DimensionsHelper.LanguageService.Symbols;

public class MetadataArealSymbol : MetadataSymbol
{
    private readonly IDeclaration _declaration;
    private Dictionary<MetadataContextLanguageKey, SyntaxNode>? _values;


    internal MetadataArealSymbol(IDeclaration declaration, string context, string language, string labelType) :
        base(SymbolKinds.MetadataArealObject, declaration)
    {
        Context = context;
        Language = language;
        _declaration = declaration;
        _values = new Dictionary<MetadataContextLanguageKey, SyntaxNode>();
        LocationMap.AddLocation(declaration.GetLocation());
        LabelType = labelType;
    }


    public override string Name => _declaration.Name;


    /// <summary>
    ///     元数据的上下文类型名
    /// </summary>
    public string Context { get; }


    /// <summary>
    ///     元数据的语言名
    /// </summary>
    public string Language { get; }


    /// <summary>
    ///     元数据的标签类型
    /// </summary>
    public string LabelType { get; }


    public IEnumerable<SyntaxNode> Value => _values?.Values ?? Enumerable.Empty<SyntaxNode>();


    public SyntaxNode? GetValue(string context, string language, string labelType)
    {
        return _values?.GetValueOrDefault(MetadataContextLanguageKey.Create(context, language, labelType));
    }


    /// <summary>
    ///     设置指定上下文、语言类型下的值节点。
    /// </summary>
    public void SetValue(string context, string language, string labelType, SyntaxNode? value)
    {
        if (value == null)
        {
            return;
        }

        MetadataContextLanguageKey key = MetadataContextLanguageKey.Create(context, language, labelType);
        _values ??= new Dictionary<MetadataContextLanguageKey, SyntaxNode>();
        if (!_values.TryAdd(key, value))
        {
            _values[key] = value;
        }
    }


    public override bool Redeclare(ISymbol symbol)
    {
        if (symbol is not MetadataArealSymbol elementSymbol)
        {
            return false;
        }

        // 后声明的覆盖已有值
        if (elementSymbol._values == null)
        {
            return true;
        }

        foreach ((MetadataContextLanguageKey key, SyntaxNode value) in elementSymbol._values)
        {
            _values ??= new Dictionary<MetadataContextLanguageKey, SyntaxNode>();
            if (!_values.TryAdd(key, value))
            {
                _values[key] = value;
            }
        }

        return true;
    }
}